/**
 * Author:  LiShibin.
 * Date:    2017/7/5 0005.
 * File：   post公共处理.
 * 说明： 后端响应格式为 {status：‘’， data: {}, msg: ''}
 * 其中data为对象或数组, status: 200成功，400失败
 */

import * as axios from 'axios'
import Qs from 'qs'
import config from '../config'
import * as storage from '../storage'

const instance = axios.create({
  baseURL: config.website + '/mobile',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  },
  transformResponse: [function (data) {
    try {
      data = JSON.parse(data)
    } catch (e) {
      console.error('请求到的数据不是json格式', data)
    }
    return data
  }],
  transformRequest: [function (data) {
    data = Qs.stringify(data)
    return data
  }]
})

async function post(url, param) {
  let key = storage.getKey()
  param = param || {}
  param.key = key // 为所有请求的参数带上key
  return new Promise((resolve, reject) => {
    // console.debug('发送请求:', url, param)
    instance.post(url, param).then(function (response) {
      response = response.data
      console.debug('请求成功：', url, param, response)
      if (response.status === 200) {
        resolve(response.data)
      } else {
        reject({status: response.status, msg: response.msg})
      }
    }).catch(e => {
      console.error('请求发生错误', url, param, e)
    })
  })
}

export {instance, post}